// useWebSocket.js
import { onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus' // 确保已经安装并引入 element-plus

const username = sessionStorage.getItem('user')
const useWebSocket = () => {
  const url = `ws://localhost:8080/imserver/${username}`
  let ws = null
  let tt = null
  let lockReconnect = false // 避免重复连接

  const heartCheck = {
    timeout: 1000 * 60 * 3,
    timeoutObj: null,
    serverTimeoutObj: null,
    start() {
      console.log('开始心跳检测')
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        console.log('心跳检测...')
        ws.send('HeartBeat:' + username)
        this.serverTimeoutObj = setTimeout(() => {
          if (ws.readyState !== 1) {
            ws.close()
          }
        }, this.timeout)
      }, this.timeout)
    }
  }

  const reconnect = () => {
    if (lockReconnect) return
    lockReconnect = true
    tt && clearTimeout(tt)
    tt = setTimeout(() => {
      console.log('执行断线重连...')
      initWebSocket()
      lockReconnect = false
    }, 4000)
  }

  /* globals MozWebSocket */
  const initWebSocket = () => {
    if ('WebSocket' in window) {
      ws = new WebSocket(url)
    } else if ('MozWebSocket' in window) {
      ws = new MozWebSocket(url)
    } else {
      console.log('您的浏览器不支持 WebSocket!')
      return
    }

    ws.onmessage = e => {
      console.log('接收消息:' + e.data)
      heartCheck.start()
      if (e.data === 'ok') {
        // 心跳消息不做处理
        return
      }
      messageHandle(e.data)
    }

    ws.onclose = () => {
      console.log('连接已关闭')
      ElMessage({
        message: '连接已关闭',
        type: 'error'
      })
      reconnect()
    }

    ws.onopen = () => {
      console.log('连接成功')
      ElMessage({
        message: '连接成功',
        type: 'success'
      })
      heartCheck.start()
    }

    ws.onerror = () => {
      console.log('数据传输发生错误')
      ElMessage({
        message: '数据传输发生错误',
        type: 'error'
      })
      reconnect()
    }
  }

  const sendMessage = (sender, reception, body, flag) => {
    const data = {
      sender,
      reception,
      body,
      flag
    }
    const msg = JSON.stringify(data)
    console.log('发送消息：' + msg)
    ws.send(msg)
  }

  const getWebSocket = () => ws

  const getStatus = () => {
    if (ws.readyState === 0) {
      return '未连接'
    } else if (ws.readyState === 1) {
      return '已连接'
    } else if (ws.readyState === 2) {
      return '连接正在关闭'
    } else if (ws.readyState === 3) {
      return '连接已关闭'
    }
  }

  onMounted(() => {
    initWebSocket()
  })

  onBeforeUnmount(() => {
    ws && ws.close()
    tt && clearTimeout(tt)
    heartCheck.timeoutObj && clearTimeout(heartCheck.timeoutObj)
    heartCheck.serverTimeoutObj && clearTimeout(heartCheck.serverTimeoutObj)
  })

  return {
    sendMessage,
    getWebSocket,
    getStatus,
    initWebSocket
  }
}

function messageHandle(message) {
  const msg = JSON.parse(message)
  switch (msg.flag) {
    case 'command':
      console.log('指令消息类型')
      break
    case 'inform':
      console.log('通知')
      break
    default:
      console.log('未知消息类型')
  }
}
